package cn.hunau.bookstore.service.impl;

import java.util.List;
import java.util.Objects;

import cn.hunau.bookstore.dao.BookDao;
import cn.hunau.bookstore.dao.impl.BookDaoImpl;
import cn.hunau.bookstore.exception.DaoException;
import cn.hunau.bookstore.pojo.Book;
import cn.hunau.bookstore.pojo.PageResult;
import cn.hunau.bookstore.pojo.ResponseResult;
import cn.hunau.bookstore.service.BookService;
import cn.hunau.bookstore.utils.JsonUtils;

/**
 * @author HuangBo
 *
 *         2022-01-22 14:20:04
 *
 */
public class BookServiceImpl implements BookService {
	private BookDao bookDao = new BookDaoImpl();

	@Override
	public PageResult<Book> page(int pageIndex, int pageSize, Object orderBy) throws DaoException {

		// 获得总记录数
		int recoderCount = bookDao.count();
		// 获得总页数
		int pageCount = recoderCount % pageSize == 0 ? recoderCount / pageSize : recoderCount / pageSize + 1;

		PageResult<Book> pageResult = new PageResult<Book>();
		pageResult.setPageIndex(pageIndex);
		pageResult.setPageSize(pageSize);
		pageResult.setRecordCount(recoderCount);
		pageResult.setPageCount(pageCount);

		int beginIndex = (pageIndex - 1) * pageSize;
		List<Book> data = null;

		// 判断查询的条件 :查询条件为null，使用默认的排序规则 按照日期排序
		if (Objects.isNull(orderBy)) {
			data = bookDao.queryBookByPageOrderByPubDate(beginIndex, pageSize);
		}
		pageResult.setData(data);
		return pageResult;
	}

	@Override
	public String setIndexBook(Book book, Integer tag) throws DaoException {
		ResponseResult result = null;
		try {
			bookDao.insertIndexBook(book, tag);
			result = new ResponseResult(true, "设置成功");
		} catch (Exception e) {
			result = new ResponseResult(false, "设置失败");
		}
		return JsonUtils.objectToJson(result);
	}

}
